﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Net;
using System.Windows.Forms;
using System.Threading;

namespace ESJImporter
{
    public partial class About : Form
    {
        private const string versionnr = "65108";
        private const string version = "0.5.2";
        private Thread updatecheck;

        public About()
        {
            InitializeComponent();
        }

        /// <summary>
        /// click anywhere to close
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void About_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        /// <summary>
        /// start check for updates in a thread
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void About_Load(object sender, EventArgs e)
        {
            label_update.Text = "Version " + version + " - checking for updates";
            updatecheck = new Thread(CheckHttp);
            updatecheck.Start();
        }

        private void About_FormClosing(object sender, FormClosingEventArgs e)
        {
            //updatecheck.Suspend();
        }

        /// <summary>
        /// check whether the current version is up-to-date
        /// 
        /// </summary>
        private void CheckHttp()
        {
            HttpWebRequest httpreq = (HttpWebRequest)System.Net.WebRequest.Create("http://edgesync.codeplex.com/releases");
            httpreq.AllowAutoRedirect = false;
            HttpWebResponse result = (HttpWebResponse)httpreq.GetResponse();
            result.Close();

            if (result.StatusCode == HttpStatusCode.Found)
            {
                string location = result.Headers["Location"];
                string versionnumber = location.Substring(location.LastIndexOf("/") + 1);
                if (versionnumber == versionnr)
                    label_update.Text = "Version "+version+" - you are running the latest version";
                else
                    label_update.Text = "Version " + version + " - an update is available; click here";
            }
            else
                label_update.Text = "Version " + version + " - update check failed";
        }

        /// <summary>
        /// go to website for downloading the update
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void label_Update_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("http://edgesync.codeplex.com/releases");
        }

    }
}
